export default class Assembly {
  constructor(data) {
    this.root = document.querySelector('#canvas')
    this.el = document.createElement('div')
    this.el.style.width = '100px'
    this.el.style.height = '100px'
    this.el.style.background = `url('${data.img}')`
    this.el.style.objectFit = 'scale-down'
    this.el.style.backgroundSize = "100% 100%";
    this.el.style.position = 'absolute'
    this.data = {
      ...data,
      positionX: 0,
      positionY: 0,
      link: [],
      id:Date.parse(new Date())
    }
    this.init = this.init.bind(this)
    this.init()
  }
  init() {
    this.el.onmousedown = (ev) => {
      // 事件对象
      ev = ev || event
      // 存值
      var disX = ev.pageX - this.el.offsetLeft
      var disY = ev.pageY - this.el.offsetTop
      var maxWidth =  parseInt(this.root.clientWidth)- this.el.clientWidth
      var maxHeight = parseInt(this.root.clientHeight)- this.el.clientHeight
   
      // 再页面上移动
      document.onmousemove = (ev) => {
        ev = ev || event
        // 移动过后的值
        var x = ev.pageX - disX
        var y = ev.pageY - disY
        
        // 判断边界值

        // 左边界
        if (x <= 0) {
          x = 0
        }
        // 右边界
        if (x >= maxWidth) {
          x = maxWidth
        }
        // 上边界
        if (y <= 0) {
          y = 0
        }
        // 下边界
        if (y >= maxHeight) {
          y = maxHeight
        }
        this.data.positionX = x
        this.data.positionY = y
        this.el.style.left = x + 'px'
        this.el.style.top = y + 'px'
      }

      // 鼠标离开把move事件清除
      document.onmouseup = function () {
        document.onmousemove = null
      }
    }
    this.el.oncontextmenu = (e)=>{
      console.log(e)
    }
    this.root.appendChild(this.el)
  }
}